// 进行axios二次封装，使用请求与响应拦截器
import axios from "axios"
import {ElMessage} from "element-plus"
import userStore from '@/store/modules/user'
import router from "@/router";
let request = axios.create({
    // 基础路径
    baseURL: import.meta.env.VITE_APP_BASE_API
});
// 请求拦截器
request.interceptors.request.use((config) => {
    let getUserStore = userStore()
    if(getUserStore.token) {
        config.headers.Authorization = getUserStore.token
    }
    // 返回配置对象
  return config
})
// 响应拦截器
request.interceptors.response.use((response) => {
    console.log(response.data.code);
    if(response.data.code == 401) {
        localStorage.clear()
        sessionStorage.clear()
        router.push({
            path: 'weixin'
        })
    }
   return response.data
}, (error) => {
    console.log(error);
    
    // 失败回调
    let message = ''
    let status = error.response.status
    switch (status) {
        case 401: 
          message = "TOKEN过期"
          break;
        case 403:
            message = "无权访问"
            break;
        case 404: 
            message="请求地址错误"
            break;
        case 500: 
           message = "服务器出现问题"
           break;
        default: 
         message="网络出现问题"
          break
    }
    // 提示错误信息
    ElMessage({
        type: 'error',
        message
    });
    return Promise.reject(error)
});

// 对外暴露
export default request;